package app

import (
	"game-server/app/common/response"
	"game-server/app/models"
	"game-server/global"

	"github.com/gin-gonic/gin"
)

// GameCommentAdd 添加评论
func GameCommentAdd(c *gin.Context) {
	var comment models.GameComment
	if err := c.ShouldBindJSON(&comment); err != nil {
		response.ValidateFail(c, err.Error())
		return
	}

	// 获取当前用户ID
	// userID := services.GetUserID(c)
	// comment.UserID = userID

	if err := global.App.DB.Create(&comment).Error; err != nil {
		response.BusinessFail(c, "添加评论失败")
		return
	}

	response.Success(c, nil)
}

// GameCommentList 获取评论列表
func GameCommentList(c *gin.Context) {
	var params struct {
		GameID uint `json:"game_id" binding:"required"`
		Page   int  `json:"page" binding:"required"`
		Limit  int  `json:"limit" binding:"required"`
	}

	if err := c.ShouldBindJSON(&params); err != nil {
		response.ValidateFail(c, err.Error())
		return
	}

	var comments []models.GameComment
	var total int64

	db := global.App.DB.Model(&models.GameComment{}).Where("game_id = ? AND status = 1", params.GameID)
	db.Count(&total)
	db.Offset((params.Page - 1) * params.Limit).Limit(params.Limit).Find(&comments)

	response.Success(c, gin.H{
		"list":  comments,
		"total": total,
	})
}

// GameCommentDel 删除评论
func GameCommentDel(c *gin.Context) {
	var params struct {
		ID     uint `json:"id" binding:"required"`
		UserID uint `json:"user_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&params); err != nil {
		response.ValidateFail(c, err.Error())
		return
	}

	// 验证评论归属权
	// userID := services.GetUserID(c)
	if err := global.App.DB.Where("id = ? AND user_id = ?", params.ID, params.UserID).Delete(&models.GameComment{}).Error; err != nil {
		response.BusinessFail(c, "删除失败")
		return
	}

	response.Success(c, nil)
}
